package com.guo.xiao.bing.controller;

import com.guo.xiao.bing.entity.ProjectType;
import com.guo.xiao.bing.entity.User;
import com.guo.xiao.bing.service.ProjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("project/type")
public class ProjectTypeController {

    @Autowired
    ProjectTypeService projectTypeService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Model model) {
        List<ProjectType> projectTypes = projectTypeService.find();
        model.addAttribute("type", projectTypes);
        return "project/type/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        return "project/type/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(String name, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if (name == null) {
            return "project/type/add";
        }
        ProjectType pt = new ProjectType();
        pt.setName(name);
        projectTypeService.save(pt);
        return "redirect:/project/type";
    }


    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        projectTypeService.delete(id);
        return "redirect:/project/type";
    }

}
